import React, {useEffect, useState} from 'react';
import './Main.scss'
import {useLocalStorage} from "../utils/useLocalStorage";
import {StyleContextProvider} from "../contexts/styleContext";
import Header from "../components/header/header";
import {splashScreen} from "../portfolio";
import SplashScreen from "./splashScreen/SplashScreen";
import '../assets/fonts/Montserrat-Regular.ttf'

const Main = () => {

    // 判断是否用户浏览器是否开启了暗黑模式（Dark Mode）。
    const darkPref = window.matchMedia("(prefers-color-scheme: dark")
    const [isDark, setIsDark] = useLocalStorage('isDark', darkPref.matches)
    // 第一次加载时的动画
    const [isShowingSplashAnimation, setIsShowingSplashAnimation] = useState(true)
    // 相当于componentDieMount
    useEffect(() => {
        // 如果存在开启动画
        if (splashScreen.enabled) {
            const splashTimer = setTimeout(() => setIsShowingSplashAnimation(false), splashScreen.duration)
            return () => clearTimeout(splashTimer)
        }
    }, [])
    // 改变theme
    const changeTheme = () => {
        setIsDark(!isDark)
    }
    return (
        <div className={isDark ? "dark-mode" : null}>
            {/*    styleContext*/}
            <StyleContextProvider value={{isDark, changeTheme}}>
                {
                    isShowingSplashAnimation && splashScreen.enabled ? (<SplashScreen/>) : (
                        <>
                            <Header/>
                        </>
                    )
                }
            </StyleContextProvider>
        </div>
    )
};

export default Main;